from django.utils.deprecation import MiddlewareMixin


class CsrfCrossDomain(MiddlewareMixin):
    """*****************************************************************************
    * Add response header to solve cross-domain interception problem;              *
    *                                                                              *
    * @Param:        response                                                      *
    * @Return:       response                                                      *
    * @LastModified: 2020-11-21                                                    *
    *                                                                              *
    * @History:                                                                    *
    *     - 2019-07-08 Lowenve: Created.                                           *
    ********************************************************************************
    """
    def process_response(self, request, response):
        response["Access-Control-Allow-Origin"] = "*"
        if request.method == "OPTIONS":
            # print("success")
            response["Access-Control-Allow-Headers"] = "Content-Type, token"
            response["Access-Control-Allow-Methods"] = "DELETE, PUT, POST, PATCH"
            print("success")
        return response


class RewardMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        data = None
        if hasattr(response, 'data'):
            data = response.data

        response.data = {
            'status': 0,
            'msg': 'OK',
            'data': data
        }
        # 因返回时已经render过response，要想让这里的修改有效，需要手动在render一次
        response._is_rendered = False
        response.render()
        return response

